//
//  AdMobView.swift
//  eBooks
//
//  Created by JunMing on 2020/2/26.
//  Copyright © 2020 赵俊明. All rights reserved.
//

import UIKit
import GoogleMobileAds

struct AdmobModel {
    var logo = "defaulticon"
    var title = "Lemon Epub Reader"
    var timeStep = ""
    var bkgUrl:String?
    
    func showAd() -> Bool {
        guard let _ = bkgUrl else { return true }
        return false
    }
}

// 执行倒计时
let duration = 8.0
class AdMobView: UIView {

    let title = UILabel()
    let logo = UIImageView(image: UIImage(named: "defaulticon"))// app logo
    let container = UIView()
    
    let bkgView = UIImageView()// 上部展示广告的View
    let timeStep = UIButton(type: .custom)// 跳过
    
    let disposeBag = DisposeBag()// 销毁
    
    lazy var banner:GADBannerView = {
        let adView = GADBannerView(adSize: kGADAdSizeBanner)
        adView.translatesAutoresizingMaskIntoConstraints = false
        adView.delegate = self
        adView.adUnitID = "ca-app-pub-5649482177498836/1892575484"
        adView.load(GADRequest())
        return adView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.white
        layoutViews()
        
        // 延迟5秒执行，如果5秒内加载广告成功取消执行，调用倒计时
        perform(#selector(bkgTimer), with: nil, afterDelay: 5)
        timeStep.addTarget(self, action: #selector(removeAdmobView), for: .touchUpInside)
    }
    
    deinit {
        print("‼️‼️‼️类\(self.className())已经释放")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func startRunTimer() {
        // 加载成功后取消后台执行
        timeStep.isHidden = false
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        Observable<TimeInterval>.timer(duration: duration, interval: 1).subscribe(onNext: { [weak self] remain in
            print("剩余：", remain)
            let canJump = remain < duration - 4
            self?.timeStep.isUserInteractionEnabled = canJump
            let title = canJump ? "跳过 \(Int(remain))" : "\(Int(remain)) 秒"
            self?.timeStep.setTitle(title, for: .normal)
        }, onCompleted: { [weak self] in
            self?.removeFromSuperview()
            print("计时结束！")
            }).disposed(by: disposeBag)
    }
    
    func startLuanchAd(rootVC:UIViewController) {
        var model = AdmobModel()
        if Tools.getVip() {
            model.bkgUrl = "http://47.105.185.248/Source/Photos/covers/jijian.jpg"
        }
        configViews(rootVC:rootVC ,model: model)
    }
    
    @objc func removeAdmobView() {
        MobClick.event("luanch_jump_buy_vip")
        removeFromSuperview()
        // banner.rootViewController?.view .routerEvent(eventName: kEbooksBuyVipEventName, info: nil)
    }
    
    @objc func bkgTimer() {
        removeFromSuperview()
    }
    
    func configViews(rootVC:UIViewController,model:AdmobModel) {
        bkgView.isHidden = model.showAd()
        banner.isHidden = !model.showAd()
        timeStep.isHidden = true
        
        if let url = model.bkgUrl {
            bkgView.setImageWith(URL(string: url), placeholder: UIImage(named: "name"), options: .progressive) { [weak self] (image, _, _, _, _) in
                if let _ = image { self?.startRunTimer() }
            }
        }else{
            banner.rootViewController = rootVC
            banner.load(GADRequest())
        }
        
        bkgView.contentMode = .scaleAspectFill
        bkgView.clipsToBounds = true
        
        title.text = model.title
        title.configLabel(textAlig:.center ,font: UIFont.regular(11),tColor:UIColor.darkGray)
        logo.image = UIImage(named: model.logo)
        logo.layer.cornerRadius = 22
        logo.layer.masksToBounds = true
        
        timeStep.setTitle(model.timeStep, for: .normal)
        timeStep.layer.cornerRadius = 17
        timeStep.backgroundColor = UIColor.black.component(0.3)
        timeStep.setTitleColor(UIColor.white, for: .normal)
        timeStep.titleLabel?.font = UIFont.systemFont(ofSize: 16)
    }
    
    func layoutViews() {
        addSubview(container)
        container.addSubview(title)
        container.addSubview(logo)
        
        addSubview(bkgView)
        addSubview(banner)
        addSubview(timeStep)
        
        container.snp.makeConstraints { (make) in
            make.height.equalTo(84)
            make.width.equalTo(snp.width)
            make.bottom.equalTo(self.snp.bottom)
        }
        
        bkgView.snp.makeConstraints { (make) in
            make.top.equalTo(snp.top)
            make.width.equalTo(snp.width)
            make.bottom.equalTo(container.snp.top)
        }
        
        banner.snp.makeConstraints { (make) in
            make.top.equalTo(snp.top)
            make.width.equalTo(snp.width)
            make.bottom.equalTo(container.snp.top)
        }
        
        ///
        logo.snp.makeConstraints { (make) in
            make.top.equalTo(container.snp.top).offset(10)
            make.width.height.equalTo(44)
            make.centerX.equalTo(container.snp.centerX)
        }
        
        title.snp.makeConstraints { (make) in
            make.height.equalTo(30)
            make.width.equalTo(snp.width)
            make.top.equalTo(logo.snp.bottom)
            make.centerX.equalTo(container.snp.centerX)
        }
        
        timeStep.snp.makeConstraints { (make) in
            make.top.equalTo(self.snp.top).offset(20)
            make.right.equalTo(self.snp.right).offset(-20)
            make.width.equalTo(70)
            make.height.equalTo(34)
        }
        
    }
}

// MARK: GADBannerViewDelegate
extension AdMobView:GADBannerViewDelegate {
    public func adViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("adViewDidReceiveAd")
        startRunTimer()
        MobClick.event("google_ad_success")
    }
    
    public func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
        print("adView - didFailToReceiveAdWithError")
        MobClick.event("google_ad_fail")
    }
    
    public func adViewWillDismissScreen(_ bannerView: GADBannerView) {
        print("adViewWillDismissScreen")
    }
    
    public func adViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("adViewWillPresentScreen")
    }
}


protocol AdMobViewProtocol { }
extension AdMobViewProtocol {
    /// 添加 Admob广告view
    func loadAdMobView(rootVC:UIViewController) {
        guard let window = UIApplication.shared.keyWindow else { return }
        let adView = AdMobView(frame: CGRect.zero)
        window.addSubview(adView)
        adView.startLuanchAd(rootVC: rootVC)
        adView.snp.makeConstraints { (make) in
            // make.edges.equalTo(backView)
            if #available(iOS 11.0, *) {
                make.top.equalTo(window.safeAreaLayoutGuide.snp.top)
                make.bottom.equalTo(window.safeAreaLayoutGuide.snp.bottom)
            }else {
                make.top.equalTo(window.snp.top)
                make.bottom.equalTo(window.snp.bottom)
            }
            make.width.equalTo(window)
        }
    }
}

import RxSwift
extension Observable where Element:FloatingPoint {
    public static func timer(duration:RxTimeInterval = RxTimeInterval.infinity,interval:RxTimeInterval = 1,ascending:Bool = false, scheduler:SchedulerType = MainScheduler.instance) -> Observable<TimeInterval> {
        let count = (duration == RxTimeInterval.infinity) ? .max:Int(duration/interval) + 1
        return Observable<Int>.timer(0, period: interval, scheduler: scheduler)
            .map { TimeInterval($0) * interval }
            .map { ascending ? $0 : (duration - $0 ) }
        .take(count)
    }
}
